# -*- coding: utf-8 -*-
# @Date   : 2021/01/27
# @File   : R72_EG_LegalpersonCreditAndChangeCheck_OTO.py
# @Author : gecong
'''eof
name:申请企业法人稳定性综合校验
code:R72_EG_LegalpersonCreditAndChangeCheck_OTO
tableName:
columnName:
groups:业务其他规则校验
dependencies:IC_DSJ_2D,EG_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
import pandas as pd
from datetime import datetime

reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']


def getTable(data, tableName, occurTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :return:该表全部数据
        '''
    table = data.get(tableName)
    if occurTimes == 0:
        if table is None or table == "":
            return [{}]
        elif isinstance(table, list) is False or len(table) == 0:
            return None
        else:
            return data.get(tableName)
    if occurTimes == 1:
        if table == "":
            return [{}]
        if table is None or isinstance(table, list) is False or len(table) == 0:
            return None
        elif len(table) == 0:
            return [{}]
        else:
            return data.get(tableName)

# 个人征信白户
def factor1():
    """1、当信贷交易信息概要（PCO）为{}时，Factor=1；
    2、信贷交易信息概要信息单元（PC02）为{}时，Factor=1；
    3、信贷交易提示信息段（PC02A）为{}时，Factor=1；
    4、信贷交易提示信息（PC02AH）为{}时，Factor=1；
    5、首笔业务发放月份（PC02AR01）在在null_type_list中
    若以上匹配都不成功，则factor1=0；
    若满足以上规则中的任意一条，则factor1=1，"""
    data = IC_DSJ_2D['data']
    PCO = getTable(data, 'PCO', 1)
    if PCO is None:
        return None
    elif PCO == [{}]:
        return 1
    else:
        PC02 = getTable(PCO[0], 'PC02', 0)
        if PC02 is None:
            return None
        elif PC02 == [{}]:
            return 1
        else:
            PC02A = getTable(PC02[0], 'PC02A', 0)
            if PC02A is None:
                return None
            elif PC02A == [{}]:
                return 1
            else:
                PC02AH = getTable(PC02A[0], 'PC02AH', 1)
                if PC02AH is None:
                    return None
                elif PC02AH == [{}]:
                    return 1
                else:
                    factor = []
                    for i in PC02AH:
                        try:
                            firstMonth = i.get('PC02AR01')
                            if firstMonth in null_type_list:
                                factor.append(None)
                            else:
                                factor.append(firstMonth)
                        except:
                            return None
                    if len(set(factor)) == 1 and None in factor:
                        return 1
                    else:
                        return 0


def FormatData(tableName):
    try:
        eg = EG_DSJ.get("data").get("R1103V3")[0].get(tableName)
        if eg in null_type_list:
            return None
        if isinstance(eg, list):
            return eg
        else:
            return None
    except:
        return None

# 统一转成datetime对象，只能转年月日的字符串
def date_format(str):
    import re
    r = re.compile(r'\D+')
    try:
        time = str[0:10]
        date = datetime.strptime(time, '%Y.%m.%d').strftime('%Y%m%d')
    except:
        try:
            date = datetime.strptime(time, '%Y-%m-%d').strftime('%Y%m%d')
        except:
            try:
                date = datetime.strptime(time, '%Y/%m/%d').strftime('%Y%m%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.strptime(tmp, '%Y%m%d').strftime('%Y%m%d')
                except:
                    date = None
    return date

def get_date_list():
    try:
        now = datetime.now()
        aaa = [(now + pd.tseries.offsets.DateOffset(months=i)).strftime('%Y%m%d') for i in [-24, 0]]
        return aaa
    except:
        return None

# 法定代表人变更次数
def factor2():
    """if 申请企业近2年内发生过法定代表人变更次数>0 then factor2= 1"""
    alter_list = FormatData("alterList")
    if alter_list is None:
        return None
    else:
        if len(alter_list) == 0:
            return 0
        else:

            change_list = [u"法人代表变更",u"负责人变更（法定代表人、负责人、首席代表、个体户经营者、投资人、合伙事务执行人等变更）",
                           u"法定代表人（负责人）变更",u"执行合伙企业事务的合伙人",u"法定代表人变更",u"法定代表人姓名",
                           u"负责人（法定代表人、首席代表、合伙事务执行人等）变更",u"法定代表人(负责人、董事长、首席代表)变更",u"负责人变更（法定代表人、负责人、首席代表、合伙事务执行人等变更）",
                           u"法定代表人（负责人、董事长、首席代表）变更",u"法定代表人",u"执行合伙企业事务的合伙",u"法定代表人(负责人、独资投资人)",
                           u"负责人变更（法定代表人、负责人、首席代表、合伙事务执行人等变更）变更",
                           u"负责人变更",u"法定代表人（负责人）",u"经营者姓名",u"负责人变更（法定代表人、负责人、首席代表、个体户经营者、投资人、合伙事务执行人等变更） "]

            result = set()
            flag = False
            date_list = get_date_list()
            for i in alter_list:
                try:
                    alt_item = i.get("altItem")
                    alt_date = date_format(i.get("altDate"))
                    if alt_date not in null_type_list and alt_item not in null_type_list:
                        flag = True
                        if date_list[0] < date_format(alt_date[0:10]) <= date_list[1] and alt_item in change_list:
                            result.add(alt_date+alt_item)
                except:
                    return None
            if not flag:
                return None
            else:
                if len(result) > 0:
                    return 1
                else:
                    return 0


def R72_EG_LegalpersonCreditAndChangeCheck_OTO():

    f1 = factor1()
    f2 = factor2()
    if f1 is None or f2 is None :
        return u'缺失值'
    else:
        if  f1 >0 and f2 > 0:
            return 2
        elif f1 >0 and f2 == 0:
            return 0
        else:
            return 1

result = R72_EG_LegalpersonCreditAndChangeCheck_OTO()
